import Worker from './woker.js'
import SparkMD5 from "spark-md5"
console.log(Worker);
function calculateFileMD5(file) {
    return new Promise((resolve, reject) => {
        const chunkSize = 1024 * 1024 * 50; // 1MB
        const spark = new SparkMD5.ArrayBuffer();
        const fileSize = file.size;
        const chunkCount = Math.ceil(fileSize / chunkSize);
        let currentChunk = 0;
        function loadNextChunk() {
            const start = currentChunk * chunkSize;
            const end = Math.min(start + chunkSize, fileSize);
            const reader = new FileReader();
            const blob = file.slice(start, end);
            reader.onload = (e) => {
                spark.append(e.target.result); // 将当前分片加入 MD5 计算
                currentChunk++;
                if (currentChunk < chunkCount) {
                    loadNextChunk(); // 继续加载下一个分片
                    const md5 = spark.end();
                    console.log('生成完成', md5);
                } else {
                    const md5 = spark.end(); // 计算最终的 MD5
                    console.log('生成完成', md5);
                    resolve(md5);
                }
            };
            reader.onerror = reject;
            reader.readAsArrayBuffer(blob);
        }

        loadNextChunk(); // 开始加载第一个分片
    });
}
window.addEventListener('load', function () {
    function startChunk(e) {
        let res = []
        let hardwareConcurrency = navigator.hardwareConcurrency - 1
        console.log(hardwareConcurrency);
        let time = new Date().getTime()
        let allHash = ""
        let file = e.target.files[0],
            chunkSize = 50 * 1024 * 1024,
            chunks = Math.ceil(file.size / chunkSize)
        let xc = Math.ceil(chunks / hardwareConcurrency)
        console.log(xc);
        let wokerAll = new Worker()
        wokerAll.postMessage({
            file: file,
            start: 0,
            end: chunks,
            type: "all",
            chunkSize: chunkSize
        })
        wokerAll.onmessage = function (event) {
            console.log(event, '完整文件解析完成');
            allHash = event.data
        }
        wokerAll.onerror = function (er) {
            console.log(er);
        }
        for (let i = 0; i < hardwareConcurrency; i++) {
            let woker = new Worker()
            console.log(woker);
            console.log(i,hardwareConcurrency,);
            woker.postMessage({
                file: file,
                start: i * xc,
                end: (i + 1) * xc > chunks ? chunks : (i + 1) * xc,
                chunkSize
            })
            woker.onmessage = function (event) {
                console.log(event, '主线程');
                res[i] = event.data
            }
            woker.onerror = function (er) {
                console.log(er);
            }
        }

    }
    let file = this.document.getElementById('file')
    file.onchange = function (e) {
        startChunk(e)
    }
})